package com.aoxon.cargo.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.bean.GsonBean;
import com.aoxon.cargo.bean.Supplier;
import com.aoxon.cargo.component.CityAndMarketDialog;
import com.aoxon.cargo.component.MyCallBack;
import com.aoxon.cargo.component.MyProgressDialog;
import com.aoxon.cargo.component.MyTextWatcher;
import com.aoxon.cargo.loader.NormalDataLoader;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.service.RegisterSupplierService;
import com.aoxon.cargo.shared.SupIndexShared;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.CheckStateUtil;
import com.aoxon.cargo.util.DataUtil;
import com.aoxon.cargo.util.EnvironmentUtil;
import com.aoxon.cargo.util.MD5;
import com.aoxon.cargo.util.ToastUtil;

/**
 * 申请注册界面Activity
 * 
 * @author ZZJ
 * 
 */
public class SupRegisterActivity extends BaseActivity implements
		NormalDataLoader.OnLoadDataListener {

	private EditText etAccount;
	private EditText etPassword;
	private EditText etComfirmPassword;
	private EditText etMobile;
	private EditText etEmail;
	private EditText etStoreName;
	private EditText etStallNumber;

	private TextView tvTitle;
	private TextView tvCity;
	private TextView tvMarket;

	private ImageView ivReturnButton;
	private ImageView ivCommitButton;

	private LinearLayout llHolder;

	private MyProgressDialog myProgressDialog;
	private MyTextWatcher myTextWatcher;
	private CityAndMarketDialog showCityAndMarketDialog;

	private GsonBean supGsonBean;

	private NormalDataLoader normalDataLoader = new NormalDataLoader(this);

	private RegisterSupplierService registerSupplierService = (RegisterSupplierService) MyServiceFactory
			.getInstance(MyServiceFactory.REGISTER_SUPPLIER);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setup();
	}


	/**
	 * 自定义方法
	 * ******************************************************************************************************************************************/

	private void setup() {
		setContentView(R.layout.sup_register);

		etAccount = (EditText) findViewById(R.id.etRegisterAccount);
		etPassword = (EditText) findViewById(R.id.etRegisterPassword);
		etComfirmPassword = (EditText) findViewById(R.id.etRegisterConfirm);
		etMobile = (EditText) findViewById(R.id.etRegisterPhone);
		etEmail = (EditText) findViewById(R.id.etRegisterEmail);
		etStoreName = (EditText) findViewById(R.id.etRegisterStore);
		etStallNumber = (EditText) findViewById(R.id.etRegisterStall);

		ivReturnButton = (ImageView) findViewById(R.id.ivPublicTitleReturn);
		ivCommitButton = (ImageView) findViewById(R.id.ivPublicTitleOther);

		tvTitle = (TextView) findViewById(R.id.tvPublicTiTle);
		tvCity = (TextView) findViewById(R.id.tvRegisterCity);
		tvMarket = (TextView) findViewById(R.id.tvRegisterMarket);
		llHolder = (LinearLayout) etAccount.getParent().getParent();

		myProgressDialog = new MyProgressDialog(SupRegisterActivity.this);
		myProgressDialog = new MyProgressDialog(this);
		myTextWatcher = new MyTextWatcher(new textWhatcherBack());
		showCityAndMarketDialog = new CityAndMarketDialog(this,
				normalDataLoader.getHandler(), tvCity, tvMarket);

		normalDataLoader.setOnloadDataListener(this);

		tvTitle.setText("申请注册");
		ivCommitButton.setImageResource(R.drawable.button_public_commit);
		ivCommitButton.setEnabled(false);

		ivReturnButton.setOnClickListener(myClickListener);
		ivCommitButton.setOnClickListener(myClickListener);
		tvCity.setOnClickListener(myClickListener);
		tvMarket.setOnClickListener(myClickListener);
		llHolder.setOnClickListener(myClickListener);

		etAccount.addTextChangedListener(myTextWatcher);
		etPassword.addTextChangedListener(myTextWatcher);
		etComfirmPassword.addTextChangedListener(myTextWatcher);
		etMobile.addTextChangedListener(myTextWatcher);
		etEmail.addTextChangedListener(myTextWatcher);
		etStoreName.addTextChangedListener(myTextWatcher);
		etStallNumber.addTextChangedListener(myTextWatcher);
		tvCity.addTextChangedListener(myTextWatcher);
		tvMarket.addTextChangedListener(myTextWatcher);

		showCityAndMarketDialog.loadCityData(false);
	}

	/**
	 * 提交申请资料
	 */
	private void commitRegisterData() {

		if (checkApplyData()) {
			normalDataLoader.load();
		}

	}

	/**
	 * 判断要提交申请注册的资料是否为空及密码比较
	 * 
	 * @param strAccount
	 * @param strPassword
	 * @param strComfirmPassword
	 * @param strPhone
	 * @param strEmail
	 * @param strStoreName
	 * @param strAddressStall
	 * @return
	 */
	private boolean checkApplyData() {
		List<String> strList = getInputList();
		if (strList.get(0).length() >= 16) {
			etAccount.requestFocus();
			ToastUtil.show(this, "帐号不能超过16个字符");
			return false;
		}
		if (strList.get(1).equals("") || strList.get(1) == null) {
			etPassword.requestFocus();
			ToastUtil.show(this, "密码不能为空");
			return false;
		}
		if (strList.get(1).length() < 6) {
			etPassword.requestFocus();
			ToastUtil.show(this, "密码不能小于6个字符");
			return false;
		}

		if (!strList.get(2).equals(strList.get(1))) {
			etComfirmPassword.requestFocus();
			ToastUtil.show(this, "两次密码不相同");
			return false;
		}
		if (!strList.get(3).matches(
				"^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$")) {
			etMobile.requestFocus();
			ToastUtil.show(this, "请填写正确的手机号码");
			return false;
		}
		if (!strList
				.get(4)
				.matches(
						"^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$")) {
			etEmail.requestFocus();
			ToastUtil.show(this, "请填写正确的邮箱地址");
			return false;
		}
		if (strList.get(5).length() >= 24) {
			etStoreName.requestFocus();
			ToastUtil.show(this, "店铺名称不能超过24个字符");
			return false;
		}
		if (strList.get(6).equals("") || strList.get(2) == null) {
			tvCity.requestFocus();
			ToastUtil.show(this, "请选择所在城市");
			return false;
		}
		if (strList.get(7).equals("") || strList.get(3) == null) {
			tvMarket.requestFocus();
			ToastUtil.show(this, "请选择批发市场");
			return false;
		}
		if (strList.get(8).equals("") || strList.get(8) == null) {
			etStallNumber.requestFocus();
			ToastUtil.show(this, "档口号码不能为空");
			return false;
		}
		return true;
	}

	/**
	 * 数据提交获得返回结果的操作
	 */
	private void commitResult() {
		try {
			if (CheckStateUtil.check(SupRegisterActivity.this, supGsonBean,
					"注册")) {
				// 保存登录的供应商用户的数据
				String strSupplier = supGsonBean.getStrJson();
				SupIndexShared.saveSupplierAndKey(strSupplier);
				Intent intent = new Intent(getBaseContext(),
						SupIndexActivity2.class);
				startActivity(intent);
				SupRegisterActivity.this.finish();
			}
		} catch (Exception e) {
			e.printStackTrace();
			ToastUtil.show(SupRegisterActivity.this, "网络连接异常");
		}
	}

	/**
	 * 获取所有输入框的文本列表
	 * 
	 * @return
	 */
	private List<String> getInputList() {
		List<String> strList = new ArrayList<String>();

		strList.add(etAccount.getText().toString());
		strList.add(etPassword.getText().toString());
		strList.add(etComfirmPassword.getText().toString());
		strList.add(etMobile.getText().toString());
		strList.add(etEmail.getText().toString());
		strList.add(etStoreName.getText().toString());
		strList.add(tvCity.getText().toString());
		strList.add(tvMarket.getText().toString());
		strList.add(etStallNumber.getText().toString());

		return strList;
	}

	/**
	 * 判断所有输入框是否都有输入
	 * 
	 * @return
	 */
	private void checkAllInput() {
		List<String> strList = getInputList();

		for (int i = 0; i < strList.size(); i++) {
			if (strList.get(i).equals("") || strList.get(i) == null) {
				ivCommitButton.setEnabled(false);
				return;
			}
		}
		ivCommitButton.setEnabled(true);
	}

	/**
	 * 文本监听的回调
	 */
	class textWhatcherBack implements MyCallBack {

		@Override
		public void callback(String choose) {
			checkAllInput();
		}

	}

	/**
	 * 系统按键的设置
	 * *****************************************************************************************************************************************/

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			Intent intent = new Intent(SupRegisterActivity.this,
					SupLoginActivity.class);
			;
			startActivity(intent);
			this.finish();
			return false;
		}
		return false;
	}

	/**
	 * 设置各控件的点击监听
	 */
	OnClickListener myClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			EnvironmentUtil.closeInputMethod(SupRegisterActivity.this);

			switch (v.getId()) {

			case R.id.ivPublicTitleReturn:
				Intent intent = new Intent(getBaseContext(),
						SupLoginActivity.class);
				startActivity(intent);
				SupRegisterActivity.this.finish();
				break;

			case R.id.ivPublicTitleOther:
				commitRegisterData();
				break;

			case R.id.tvRegisterCity:
				showCityAndMarketDialog.showCity();
				break;

			case R.id.tvRegisterMarket:
				showCityAndMarketDialog.showMarket();
				break;

			default:
				break;
			}

		}
	};

	@Override
	public void beforeLoad() {
		// TODO Auto-generated method stub
		myProgressDialog.show("提示", "注册中...");
	}

	@Override
	public void toLoad(Message msg) throws Exception {
		// TODO Auto-generated method stub
		List<String> strList = getInputList();
		String key = new MD5().encrypt(strList.get(1));
		final Supplier supplier = new Supplier(strList.get(0), key,
				strList.get(3), strList.get(4), strList.get(5), strList.get(6),
				strList.get(7), strList.get(8));
		supGsonBean = registerSupplierService.execute(supplier);
		System.out.println(DataUtil.gson.toJson(supGsonBean));
		msg.what = MyStateUtil.REGIEST_RESULT;
	}

	@Override
	public void afterLoad(int state) {
		// TODO Auto-generated method stub
		myProgressDialog.cancle();
		switch (state) {
		case MyStateUtil.REGIEST_RESULT:
			commitResult();
			break;

		case MyStateUtil.GET_CITY_RESULT:
			showCityAndMarketDialog.showCity();
			break;
		case MyStateUtil.GET_MARKET_RESULT:
			showCityAndMarketDialog.showMarket();
			break;
		case MyStateUtil.RETURN_FAIL:
			ToastUtil.show(getBaseContext(), "无对应数据");
			break;
		case MyStateUtil.NOT_NET_CONNECTION:
			ToastUtil.show(getBaseContext(), "无网络连接");
			break;
		case MyStateUtil.ERROR_NET_CONNECTION:
			ToastUtil.show(getBaseContext(), "网络连接异常");
			break;
		default:
			break;
		}
	}

}
